package com.itfitness.googlemappoi.http
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

import okhttp3.OkHttpClient

import okhttp3.logging.HttpLoggingInterceptor
import java.io.UnsupportedEncodingException
import java.net.URLDecoder
import java.util.concurrent.TimeUnit


object RetrofitManger {
    private const val BASE_URL = "https://maps.googleapis.com/" //接口地址
    private var mRetrofit: Retrofit
    init {
        val interceptor = HttpLoggingInterceptor { message ->
            try {
                val msg: String = URLDecoder.decode(message, "utf-8")
            } catch (e: UnsupportedEncodingException) {
                e.printStackTrace()
            }
        }
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        /**okhttp默认时间10秒 请求时间较长时，重新设置下  **/
        /**okhttp默认时间10秒 请求时间较长时，重新设置下   */
        val builder = OkHttpClient.Builder()
        builder.connectTimeout(15, TimeUnit.SECONDS)
        builder.readTimeout(20, TimeUnit.SECONDS)
        builder.writeTimeout(20, TimeUnit.SECONDS)
        builder.retryOnConnectionFailure(true)
        val client = builder.build()
        mRetrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
//            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(client)
            .build()
    }

    fun <T> getApiService(reqServer: Class<T>): T {
        return mRetrofit.create(reqServer)
    }

    /**
     * 获取默认的接口
     */
    fun getApiService(): ApiService {
        return mRetrofit.create(ApiService::class.java)
    }
}